/**
 * 
 */
package com.novatialabs.qttt.gwt.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author nchalko
 * 
 */
public class GameCellWidget extends Composite  implements HasMarkHandlers {
  
  interface MyUiBinder extends UiBinder<Widget, GameCellWidget> {}
  private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

  private final int cellNumber;
  
  @UiField
  Label number ;
  
  @UiField
  Label marks ;

  public GameCellWidget(int cellNumber) {
    initWidget(uiBinder.createAndBindUi(this));
    this.cellNumber = cellNumber;
    
    number.setText(cellNumber + "");

  }

  @UiHandler ("panel")
  void handleClick(ClickEvent click){
    fireEvent(new MarkEvent(cellNumber));
  }

  public int getCellNumber() {

    return cellNumber;
  }

  public void display(GameModel game) {
    StringBuilder sb = new StringBuilder();
    int n = 0;
    for (Move m : game.getMoves()) {
    	n++;
        if(m.getFirstMark()  == cellNumber
        || m.getSecondMark() == cellNumber) {
        	appendMark(sb, n);
        }
      marks.setText(sb.toString());
    }
  }

  private void appendMark(StringBuilder sb, int n) {
  	if(n%2 == 1)	sb.append("X");
  	else			sb.append("O");
      sb.append(n);
  }

  public HandlerRegistration addMarkHandler(MarkHandler handler) {
    return addHandler(handler,MarkEvent.getType());
  }

}
